package cn.nn200433.common;

import cn.hutool.cache.impl.LFUCache;
import cn.hutool.core.text.NamingCase;
import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * 百度翻譯
 *
 * @author song_jx
 * @date 2022年03月24日 0024 10:54:30
 */
public class BaiDuFy {

    private static final Log log = LogFactory.get();

	private static LFUCache<String, String> cache = new LFUCache<String, String>(1000);
    private static final String APP_SALT = "swagger";

    private String appId;
    private String appKey;

	private static final String url = "https://fanyi-api.baidu.com/api/trans/vip/translate";

	public BaiDuFy(String appId, String appKey) {
		this.appId = appId;
		this.appKey = appKey;
	}

	/**
	 * 翻译
	 *
	 * @param q 问
	 * @return {@link String }
	 * @author song_jx
	 */
	public String translate(String q) {
		final String query = StrUtil.replace(NamingCase.toUnderlineCase(q), StrUtil.UNDERLINE, StrUtil.SPACE);
		String result = cache.get(query);
		if (StrUtil.isNotBlank(result)) {
            log.info("======> 【百度翻译】 缓存命中 单词 = {} | 结果 = {}", query, result);
			return result;
		}

		Map<String, Object> paramsMap = new HashMap<String, Object>(6);
		paramsMap.put("q", query);
		paramsMap.put("from", "en");
		paramsMap.put("to", "zh");
		paramsMap.put("appid", this.appId);
		paramsMap.put("salt", APP_SALT);
		paramsMap.put("sign", SecureUtil.md5(this.appId + query + APP_SALT + this.appKey));

		String post = HttpUtil.post(url, paramsMap);
		log.info("======> 【百度翻译】 单词 = {} | 结果 = {}", query, post);
		JSONObject resultObj = JSON.parseObject(post);
		String eCode = resultObj.getString("error_code");
		if (StrUtil.isNotBlank(eCode)) {
			return StrUtil.EMPTY;
		}
		String dst = UnicodeUtil.toString(resultObj.getJSONArray("trans_result").getJSONObject(0).getString("dst"));
        log.info("======> 【百度翻译】 最终取值 = {}", dst);
		cache.put(query, dst);
		return dst;
	}

}
